<template>
  <div class="no-padding app-container spect-root">

    <div class="process-container">
      <process></process>
    </div>
    <div class="tree-data-container">
      <lst-page-container>

        <template slot="query">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="检查名称" prop="inspectName">
              <el-input
                  v-model="queryParams.inspectName"
                  placeholder="请输入检查名称"
                  clearable
                  style="width: 240px"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="检查状态" prop="inspectState">
              <el-select v-model="queryParams.inspectState" placeholder="检查状态" clearable>
                <el-option
                    v-for="dict in dict.type.enum_inspect_state"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button v-hasRole="{role: ['A:B:C','A:C:D'], logical: LOGICAL.AND}" type="primary" icon="el-icon-plus"
                         size="mini" @click="handleAdd(null)">新增
              </el-button>
            </el-form-item>
          </el-form>
        </template>

        <!--        <template slot="handel">-->
        <!--          <el-row class="handle-container" :gutter="10">-->
        <!--            <el-col :span="1.5">-->
        <!--              <el-button-->
        <!--                  type="primary"-->
        <!--                  plain-->
        <!--                  icon="el-icon-plus"-->
        <!--                  size="mini"-->
        <!--                  @click="handleAdd"-->
        <!--              >新增-->
        <!--              </el-button>-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </template>-->

        <template slot="table">
          <el-scrollbar>
            <el-tree
                v-loading="loading"
                v-if="treeShowFlag"
                :props="treeProps"
                :load="loadNode"
                node-key="nodeKey"
                :default-expanded-keys="keys"
                :indent="paddingLeft"
                class="big-tree"
                lazy>
              <div class="node-container" slot-scope="{ node, data }">
                <parent-node :show-level="showLevel" :padding-left="paddingLeft" @showInfo="showInfo"
                             v-if="node.level==1"
                             :data="data"></parent-node>
                <child-node :show-level="showLevel" :padding-left="paddingLeft" @submitEvent="eventHandel" v-else
                            :data="data"
                            :node-info="node"></child-node>
              </div>
            </el-tree>
          </el-scrollbar>
        </template>

        <template slot="pageDisplay">
          <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
          />
        </template>
      </lst-page-container>
    </div>

    <el-dialog ref="dialog" title="选择组织" show-close modal :visible.sync="open" width="1100px" append-to-body>
      <div v-if="open" class="app-container">
        <org-list @change="handleSelectionChange"></org-list>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog ref="dialog" title="接收任务" show-close modal :visible.sync="openReception" width="500px"
               append-to-body>
      <div v-if="openReception" class="app-container">
        <el-form ref="receptionFormRef" :model="receptionForm" :rules="receptionRules" label-width="80px">
          <el-form-item label="认可时间" prop="agreementTime">
            <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                            v-model="receptionForm.agreementTime" clearable style="width: 100%; "></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReception">确 定</el-button>
        <el-button @click="cancelReception">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ParentNode from "@/views/securityCheck/ztDefectInspect/components/parentNode.vue";
import ChildNode from "@/views/securityCheck/ztDefectInspect/components/childNode.vue";
import process from "@/views/securityCheck/ztDefectInspect/components/process.vue";
import guid from "@/utils/guid";
import {
  acceptTask,
  appendOrg,
  getDefectInspectList,
  queryChildTaskNodes,
  queryResponsibleTaskNodes, startNode
} from "@/api/securityCheck/ztDefectInspect";
import {INSPECT_STATE} from "@/constantData";
import {isArr} from "@/utils/arrayUtil";
import OrgList from "@/views/components/OrgList.vue";

export default {
  dicts: ['enum_inspect_state'],
  name: "ztDefectInspect_list",
  components: {
    ParentNode,
    ChildNode,
    process,
    OrgList
  },
  data() {
    return {
      keys: [],
      showLevel: 0,
      txtLevel: 2,
      INSPECT_STATE,
      paddingLeft: 30,
      treeProps: {
        label: 'title',
        children: 'children'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inspectName: null,
        inspectState: null,
      },
      dataList: [],
      total: 0,
      treeShowFlag: true,
      loading: false,

      open: false,
      bufferCheckList: [],
      currentDdf: null,

      openReception: false,
      receptionForm: {
        agreementTime: null
      },
      receptionRules: {
        agreementTime: [
          {required: true, message: "认可时间不能为空", trigger: "blur"}
        ],
      }
    }
  },
  methods: {

    eventHandel(eventItem, nodeData, nodeInfo) {
      let {handelCode, funName, param} = eventItem
      if (!this[funName] || typeof this[funName] !== 'function') return;
      this[funName]({nodeData, nodeInfo, param, handelCode})
    },
    startExamine({nodeData, nodeInfo, param, handelCode}) {
      let {instanceNo, serialNo: nodeSerialNo} = nodeData;
      let owner = this
      this.$modal.confirm('是否确认启动').then(function () {
        owner.startLoading('正在加载....')
        return startNode({instanceNo, nodeSerialNo});
      }).then(() => {
        owner.resetQuery()
        this.$modal.msgSuccess("启动成功");
      }).catch(() => {
      }).finally(() => {
        owner.endLoading()
      });
    },
    reception({nodeData, nodeInfo, param, handelCode}) {
      let {instanceNo, serialNo: nodeSerialNo} = nodeData;
      this.receptionForm = {
        instanceNo,
        nodeSerialNo,
        agreementTime: null,
      }
      this.openReception = true
    },
    cancelReception() {
      this.openReception = false
    },
    submitReception() {
      let owner = this
      this.$refs["receptionFormRef"].validate(valid => {
        if (valid) {
          owner.startLoading('正在加载....')
          acceptTask(owner.receptionForm).then(res => {
            owner.$modal.msgSuccess("接收成功");
            owner.openReception = false
            owner.resetQuery()
          }).finally(() => {
            owner.endLoading()
          });
        }
      })
    },
    handleSelectionChange(selection) {
      this.bufferCheckList = _.cloneDeep(selection)
    },
    cancel() {
      this.open = false
    },
    submitForm() {
      this.loading = true
      let {
        bufferCheckList: orgList,
        currentDdf: {nodeData: {inspectId: id, instanceNo, serialNo: parentNodeNo, nodeId}}
      } = this;
      if (!isArr(orgList)) {
        this.$modal.msgError("请选择组织数据");
        return
      }
      appendOrg({orgList, id, instanceNo, parentNodeNo, planCompletedTime: '2023-06-20'}).then(res => {
        this.$modal.msgSuccess("操作成功");
      }).finally(() => {
        this.loading = false
        this.cancel()
      })
    },
    addTo({nodeData, nodeInfo, param, handelCode}) {
      this.currentDdf = {nodeData, nodeInfo, param, handelCode}
      this.open = true
    },
    showInfo(data) {
      let {inspectState, id} = data;
      if (inspectState == this.INSPECT_STATE.draft) {
        this.handleAdd(id)
      } else {
        this.handleInfo(id)
      }
    },
    goPage({nodeData, nodeInfo, param, handelCode}) {
      let {path} = param;
      if (path == null || path === '') return;
      let {instanceNo, serialNo: nodeSerialNo, inspectId} = nodeData
      this.$router.push({path, query: {handelCode, instanceNo, nodeSerialNo, inspectId}})
    },
    loadNode(node, resolve) {
      this.loading = true
      let owner = this
      let {showLevel} = this
      //  根节点
      if (node.level === 0) {
        owner.keys = []
        getDefectInspectList(this.queryParams).then(res => {
          owner.total = res.total;
          owner.loading = false;
          owner.loading = false
          let resData = res.rows.map(item => {
            const nodeKey = `key${guid()}`
            item.inspectId = item.id
            item.nodeKey = nodeKey
            if (node.level < showLevel) {
              owner.keys.push(nodeKey)
            }
            return item
          })
          return resolve(resData)
        })
      } else if (node.level === 1) {
        let {data: {inspectId}} = node
        queryResponsibleTaskNodes({id: inspectId}).then(res => {
          const data = owner.getTreeResData(res, node)
          owner.loading = false
          resolve(data)
        })
      } else {
        let {data: {inspectId, levelTxt, serialNo: parentNo, instanceNo}} = node
        queryChildTaskNodes({parentNo, instanceNo}).then(res => {
          const data = owner.getTreeResData(res, node)
          owner.loading = false
          resolve(data)
        })
      }
    },
    getTreeResData(res, node) {
      let {showLevel, txtLevel} = this
      let {data: {inspectId, levelTxt}} = node
      let {data: {isRoot, nodeViewList}} = res
      const data = nodeViewList.map((item, index) => {
        const nodeKey = `key${guid()}`
        item.nodeId = item.serialNo;
        item.title = item.nodeName
        item.nodeType = item.taskNodeTypeCode
        item.inspectId = inspectId
        const cLevelTxt = `${node.level + 1 > txtLevel ? `${levelTxt}${index + 1}.` : ''}`;
        item.cLevelTxt = cLevelTxt
        item.nodeKey = nodeKey
        item.isRoot = isRoot
        item.level = node.level + 1
        if (node.level < showLevel) {
          this.keys.push(nodeKey)
        }
        return item
      })
      return data
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(id = null) {
      const query = id != null ? {id} : null
      this.$router.push({path: '/securityCheck/ztDefectInspectEdit', query})
    },
    /** 详情 */
    handleInfo(inspectId) {
      const query = inspectId != null ? {inspectId} : null
      this.$router.push({path: '/securityCheck/ztDefectInspectInfo', query})
    },
    reset() {
      this.treeShowFlag = false;
      let owner = this
      setTimeout(() => {
        owner.treeShowFlag = true;
      }, 5)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.reset();
    },
  },
  created() {

  },
}
</script>

<style lang="scss" scoped>
.app-container.spect-root {
  display: flex;
  flex-direction: column;

  ::v-deep .list-page-container-root {
    .header {
      height: 35px;
    }

    .table-container {
      height: calc(100% - 85px);
    }
  }

  .process-container, .tree-data-container {
    width: 100%;
  }

  .process-container {
    height: 140px;
  }

  .tree-data-container {
    padding: 20px;
    box-sizing: border-box;
    height: calc(100% - 140px);

    ::v-deep .el-tree.big-tree {
      .el-tree-node {
        background: rgba(250, 251, 252, 1);
        margin-bottom: 10px;

        &.is-expanded {
          .last-line.hidden {
            visibility: visible !important;
          }

          .parent-node-root {
            .txt-container {
              border-bottom: 1px solid #f5eded;
            }
          }
        }

        &.is-expanded.is-current.is-focusable, &:hover, &:focus, &:active {
          .el-tree-node__content {
            background: rgba(250, 251, 252, 1);
          }
        }

        .el-tree-node__content {
          height: max-content;
          width: 100%;
          padding: 0;

          .el-tree-node__expand-icon {
            display: none;
          }

          .node-container {
            width: 99%;
            box-sizing: border-box;
          }

          .el-tree-node__loading-icon {
            display: none;
          }
        }
      }
    }
  }
}
</style>
